import { addDepositApi, editDepositApi } from "@/api/waybillManagement/depositRegister";
import { getDeptAccountApi } from "@/api/financialManagement/receivable/waterVerification";

import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { Ref } from "vue";
export default function OperationHook(state: {
  formState: DepositRegister.AddForm;
  formDataRef: Ref<any>;
  emit: any;
  passData: Ref<DepositRegister.ListRows>;
  loading: Ref<boolean>;
  type: Ref<number>;
  accountOpts: Ref<Array<{ label: string; value: string }>>;
  companyOpts: Ref<Array<{ label: string; value: string }>>;
}) {
  const { formState, formDataRef, emit, passData, loading, type, accountOpts, companyOpts } = state;
  const { resetFields } = FormHook({ formState });
  const onFinish = () => {
    // Parameters<typeof addDepositApi>[0]
    const params: any = {
      ...formState,
      proceedsTime: dayjs(formState.proceedsTime).format("YYYY-MM-DD HH:mm:ss"),
      deptId: formState.deptId
      // proceedsAccount: formState.accountId[1]
    };
    if (formState.image && formState.image.length) params.image = (formState.image as string[]).join(",");
    else params.image = "";

    let requestFn;
    if (type.value === 1) {
      Reflect.deleteProperty(params, "id");
      requestFn = addDepositApi;
    } else {
      params.id = passData.value.id;
      requestFn = editDepositApi;
    }
    loading.value = true;
    requestFn(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("操作成功!");
          emit("submit");
        }
      })
      .finally(() => (loading.value = false));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const filterOption = (input: string, option: any) => {
    return String(option.label).toLowerCase().indexOf(String(input).toLowerCase()) >= 0;
  };

  const getCompanyAndAccount = (e: string) => {
    return getDeptAccountApi(e).then((res: any) => {
      const { data } = res;
      const { deptAccounts } = data[0];
      //获取经营单位列表
      companyOpts.value = [{ label: data[0].deptName, value: data[0].deptId }];
      formState.deptId = data[0].deptId;
      //获取收款账户列表
      accountOpts.value = deptAccounts.map((t: any) => {
        return {
          name: t.name,
          id: t.id,
          ...t
        };
      });
    });
  };

  const changeCompany = (e: string) => {
    formState.deptId = "";
    // formState.accountId = "";
    getCompanyAndAccount(e);
  };

  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    filterOption,
    getCompanyAndAccount,
    changeCompany
  };
}
